package com.cjp.run.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cjp.utils.FileUtils;

@RestController
public class LoginController {
	@RequestMapping("/loginService")
	@ResponseBody
	public String loginService(@RequestBody String params,HttpServletRequest request){
		JSONObject result=new JSONObject();
		JSONObject paramsJson=JSONObject.parseObject(params);
		String username=paramsJson.getString("username");
		String password=paramsJson.getString("password");
		JSONObject json=FileUtils.readUser();
		if(json==null){
			result.put("code", 500);
			result.put("message", "用户不存在");
			return result.toString();
		}else{
			JSONArray array=json.getJSONArray("data");
			for(int i=0;i<array.size();i++){
				JSONObject user=array.getJSONObject(i);
				if(user.getString("username").equals(username)){
					if(user.getString("password").equals(password)){
						result.put("code", 200);
						request.getSession().setAttribute("user", username);
						return result.toString();
					}else{
						result.put("code", 500);
						result.put("message", "密码不正确");
						return result.toString();
					}
				}
			}
			result.put("code", 500);
			result.put("message", "用户名不存在");
			return result.toString();
		}
	}
	@RequestMapping("/getUser")
	@ResponseBody
	public String getUser(HttpServletRequest request){
		JSONObject json=new JSONObject();
		json.put("user", request.getSession().getAttribute("user"));
		return json.toString();
	}
	
	@RequestMapping("/logout")
	@ResponseBody
	public String logout(HttpServletRequest request,HttpServletResponse response){
		JSONObject json=new JSONObject();
		request.getSession().invalidate();
		return json.toString();
	}
}
